package com.genersoft.iot.vmp.vmanager.gb28181.talkback;

import com.genersoft.iot.vmp.common.StreamInfo;
import com.genersoft.iot.vmp.conf.UserSetting;
import com.genersoft.iot.vmp.gb28181.transmit.callback.DeferredResultHolder;
import com.genersoft.iot.vmp.gb28181.transmit.callback.RequestMessage;
import com.genersoft.iot.vmp.service.ITalkbackService;
import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
import com.genersoft.iot.vmp.vmanager.bean.WVPResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author ：
 * @date ：Created in 2023/3/16 10:10
 * @description：语音对讲controller
 * @modified By：
 * @version: ${1.0.0}
 */
@Tag(name  = "国标对讲")
@CrossOrigin
@RestController
@RequestMapping("/api/talkback")
public class TalkbackController {

    @Autowired
    private ITalkbackService talkbackService;
    @Autowired
    private UserSetting userSetting;
    @Autowired
    private DeferredResultHolder resultHolder;
    /**
     * 获取webrtc推流地址
     *
     * @param deviceId
     * @param channelId
     * @return
     */
    @Operation(summary = "获取webrtc推流地址")
    @Parameter(name = "deviceId", description = "设备国标编号", required = true)
    @Parameter(name = "channelId", description = "通道国标编号", required = true)
    @GetMapping("/getWebRtcAddr/{deviceId}/{channelId}")
    public WVPResult getWebRtcAddr(@PathVariable("deviceId") String deviceId, @PathVariable("channelId") String channelId) {
        return talkbackService.getWebRtcAddr(deviceId,channelId);
    }

    /**
     * 开始语音对讲
     *
     * @param deviceId
     * @param channelId
     * @param app
     * @param stream
     * @return
     */
    @Operation(summary = "开始语音对讲")
    @Parameter(name = "deviceId", description = "设备国标编号", required = true)
    @Parameter(name = "channelId", description = "通道国标编号", required = true)
    @Parameter(name = "app", description = "流name", required = true)
    @Parameter(name = "stream", description = "流id", required = true)
    @Parameter(name = "model", description = "对讲模式：0国标模式，1大华TALK模式", required = true)
    @GetMapping("/start/{deviceId}/{channelId}/{app}/{stream}/{model}")
    public DeferredResult<Object> start(@PathVariable("deviceId") String deviceId, @PathVariable("channelId") String channelId,
                                        @PathVariable("app") String app, @PathVariable("stream") String stream, @PathVariable("model") Integer model) {

        RequestMessage requestMessage = new RequestMessage();
        String key = DeferredResultHolder.CALLBACK_CMD_PROXY + app + stream;
        requestMessage.setKey(key);
        String uuid = UUID.randomUUID().toString();
        requestMessage.setId(uuid);
        DeferredResult<Object> result = new DeferredResult<>(userSetting.getAudioTimeout().longValue());
        resultHolder.put(key, uuid, result);

        //超时回复
        result.onTimeout(() -> {
            WVPResult<StreamInfo> wvpResult = new WVPResult<>();
            wvpResult.setCode(ErrorCode.ERROR100.getCode());
            wvpResult.setMsg("语音对讲超时，请稍后再试");
            requestMessage.setData(wvpResult);
            resultHolder.invokeAllResult(requestMessage);
        });
        //大华talk模式
        if (model == 1) {
            talkbackService.DHTalk(deviceId,channelId,stream,app,(code, msg, obj)-> {
                if (code == ErrorCode.SUCCESS.getCode()) {
                    requestMessage.setData(WVPResult.success());
                    resultHolder.invokeAllResult(requestMessage);
                } else {
                    //失败
                    requestMessage.setData(WVPResult.fail(code, msg));
                    resultHolder.invokeAllResult(requestMessage);
                }
            });
        } else {
            //下发对讲信令
            talkbackService.talk(deviceId, channelId, stream, app, (code, msg, obj) -> {
                if (code == ErrorCode.SUCCESS.getCode()) {
                    requestMessage.setData(WVPResult.success());
                    resultHolder.invokeAllResult(requestMessage);
                } else {
                    //失败
                    requestMessage.setData(WVPResult.fail(code, msg));
                    resultHolder.invokeAllResult(requestMessage);
                }
            });
        }

        return result;
    }

    @PostMapping("/sendAudioFileToDevice/{deviceId}/{channelId}/{streamId}")
    public WVPResult sendAudioFileToDevice(@PathVariable("deviceId") String deviceId,@PathVariable("channelId") String channelId,@PathVariable("streamId") String streamId,@RequestParam("mp3File") MultipartFile mp3File){
        return talkbackService.sendAudioFileToDevice(deviceId,channelId,streamId,mp3File);
    }


}
